#!/bin/ksh
#******************************************************************************
# 
#      filename:  filecount
#
#   description:  prints counts for different filetypes
#
#        author:  Szechy, Jared
#      login id:  cps444-n1.10
#
#         class:  CPS 444
#    instructor:  Perugini
#    assignment:  Homework #6
#
#      assigned:  November 09, 2009 
#           due:  November 16, 2009
#
#******************************************************************************

while getopts fxld o
do case "$o" in
   f) fileflag="1";;
   x) execflag="1";;
   l) linkflag="1";;
   d) dirflag="1";;
   [?])  print >&2 "Usage: filecount [-dflx] [directory ...]"
         exit 1;;
   esac
done

if [[ $fileflag -ne 1 && $execflag -ne 1 && $linkflag -ne 1 \
      && $dirflag -ne 1 ]]; then
   fileflag=1;
   execflag=1;
   linkflag=1;
   dirflag=1;
fi

shift $OPTIND-1

if [[ $# = 0 ]]; then
   output=""
   if [[ $fileflag -eq 1 ]]; then      
      numFiles=$(ls -F -1 | egrep '.*[^\*/@]$' | wc -l)
      output="$numFiles ordinary"
   fi 
   if [[ $execflag -eq 1 ]]; then
      numExec=$(ls -F -1 | egrep '.*\*$' | wc -l)
      output="$output  $numExec executable"
   fi
   if [[ $linkflag -eq 1 ]]; then  
      numLinks=$(ls -F -1 | egrep '.*@$' | wc -l)
      output="$output  $numLinks links"
   fi   
   if [[ $dirflag -eq 1 ]]; then
      numDir=$(ls -F -1 | egrep '.*/$' | wc -l)
      output="$output  $numDir directories"
   fi  
   print ".:  $output"
   exit 0
fi

while [[ $# > 0 ]]; do
   if [[ -d $1 ]]; then
      output=""
      if [[ $fileflag -eq 1 ]]; then      
         numFiles=$(ls -F -1 $1 | egrep '.*[^\*/@]$' | wc -l)
         output="$numFiles ordinary"
      fi 
      if [[ $execflag -eq 1 ]]; then
         numExec=$(ls -F -1 $1 | egrep '.*\*$' | wc -l)
         output="$output  $numExec executable"
      fi
      if [[ $linkflag -eq 1 ]]; then  
         numLinks=$(ls -F -1 $1 | egrep '.*@$' | wc -l)
         output="$output  $numLinks links"
      fi   
      if [[ $dirflag -eq 1 ]]; then
         numDir=$(ls -F -1 $1 | egrep '.*/$' | wc -l)
         output="$output  $numDir directories"
      fi  
      print "$1:  $output"
      shift 1
   else
      print >&2 "Usage: filecount: Invalid directory: $1"
      exit 2
   fi
done
exit 0
